//
//  RegisterViewController.m
//  舟航007机车卫士
//
//  Created by admin on 15/11/9.
//  Copyright (c) 2015年 redoor. All rights reserved.
//

#import "RegisterViewController.h"
#import "PopLoadMsg.h"
#import "PopMsg.h"
#import "NameViewController.h"
#import "SetPasswordViewController.h"

@interface RegisterViewController () <UITextFieldDelegate>
{
    UITextField *_fieldPhone;
    UITextField *_fieldCode;
    UIButton *_btnGetCode;
    UILabel *_tipLabel;
    UIButton *_btnNext;
    UILabel *_timeLabel;
    NSTimer *_timer;
    NSString *_message;
    NSInteger k;
    NSString *result;
    NSInteger flagPhone;
}
@end

@implementation RegisterViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    [self addTitle:@"账号激活"];
    [self configView];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden = YES;
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_timer invalidate];
    _timer = nil;
}

- (void)configView
{
    //提示：手机号码验证
    UILabel *label_phoneVerify = [self createLabelFrame:CGRectMake(20*W, SCREEN_HEIGHT/2-120*H, SCREEN_WIDTH-40*W, 30*H) title:@"手机号码验证" font:[UIFont systemFontOfSize:26]];
    [self.view addSubview:label_phoneVerify];
    
    //手机号输入框
    _fieldPhone = [self createTextFieldFrame:CGRectMake(20*W, CGRectGetMaxY(label_phoneVerify.frame)+20*H, SCREEN_WIDTH-40*W, 35*H) title:nil placeholder:@"输入手机号"];
    _fieldPhone.delegate = self;
    _fieldPhone.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:_fieldPhone];
    
    //验证码输入框
    _fieldCode = [self createTextFieldFrame:CGRectMake(20*W, CGRectGetMaxY(_fieldPhone.frame)+15*H, (CGRectGetWidth(_fieldPhone.frame)-5)*0.65, 35*H) title:nil placeholder:@"输入验证码"];
    _fieldCode.delegate = self;
    _fieldCode.keyboardType = UIKeyboardTypeNumberPad;
    [self.view addSubview:_fieldCode];
    
    //获取验证码按钮
    _btnGetCode = [self createBtnFrame:CGRectMake(20*W+CGRectGetWidth(_fieldCode.frame)+5, CGRectGetMaxY(_fieldPhone.frame)+15*H, (CGRectGetWidth(_fieldPhone.frame)-5)*0.35, 35*H) title:@"获取验证码" bgImageName:@"3pic_getcode" selectedImageName:@"3pic_getcode_on" target:self action:@selector(getCode:)];
    [self enableButton:_btnGetCode];
    [self.view addSubview:_btnGetCode];
    
    //显示验证码倒计时label
    _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0.05*CGRectGetWidth(_btnGetCode.frame), 0, 0.9*CGRectGetWidth(_btnGetCode.frame), CGRectGetHeight(_btnGetCode.frame))];
    _timeLabel.backgroundColor = [UIColor clearColor];
    _timeLabel.text = @"";
    _timeLabel.textColor = [UIColor whiteColor];
    _timeLabel.font = [UIFont systemFontOfSize:13];
    _timeLabel.textAlignment = 1;
    [_btnGetCode addSubview:_timeLabel];
    _timeLabel.hidden = YES;
    
    //验证码错误提示信息
    _tipLabel = [self createLabelFrame:CGRectMake(20*W, CGRectGetMaxY(_fieldCode.frame)+15*H, SCREEN_WIDTH-40*W, 15*H) title:@"" font:[UIFont systemFontOfSize:15]];
    _tipLabel.textColor = [UIColor cyanColor];
    [self.view addSubview:_tipLabel];
    _tipLabel.hidden = YES;
    
    //下一步按钮
    _btnNext = [self addNextBtnTarget:self action:@selector(btnNextClicked:)];
    [self disableButton:_btnNext];
}

#pragma mark - 网络请求
//获取验证码请求
- (void)verifyCodeRequest
{
    PopLoadMsg *loadmsg = [PopLoadMsg new];
    [loadmsg delayLoadImages];
    
    NSDictionary *paramdic = @{@"loginId":_fieldPhone.text,@"type":@"0"};
    NSString *url = [urlstring stringByAppendingString:@"getVerifyCode.do"];
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        [loadmsg delayImagesRemove];
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSLog(@"dic = %@", dic);
        
        NSInteger flag = [[dic objectForKey:@"flag"] integerValue];
        NSString *msg = [dic objectForKey:@"msg"];
        result = [dic objectForKey:@"result"];
        if (flag == 0) {
            //获取验证码成功
            NSLog(@"result = %@", result);
            _btnGetCode.enabled = NO;
            [_btnGetCode setTitle:@"" forState:UIControlStateNormal];
            _timeLabel.hidden = NO;
            _tipLabel.hidden = YES;
            _fieldCode.text = @"";
            [self disableButton:_btnNext];
            k = 60;
            _timeLabel.text = [NSString stringWithFormat:@"剩余时间%i秒",k];
            if (_timer == nil) {
                _timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target:self selector:@selector(timer:) userInfo:nil repeats:YES];
            }
        }
        else {
            [PopMsg showMessage:msg Lasttime:1.0f];
        }
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        [loadmsg delayImagesRemove];
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
    }];
}

//验证手机号请求
- (void)verifyPhoneRequest
{
    PopLoadMsg *loadmsg = [PopLoadMsg new];
    [loadmsg delayLoadImages];
    
    NSDictionary *paramdic = @{@"loginId":_fieldPhone.text,
                             @"verifyCode":_fieldCode.text};
    NSString *url = [urlstring stringByAppendingString:@"verifyPhoneNum.do"];
    
    [K_AppDelegate GenerateHTTPRequestWithUrl:url withParam:paramdic success:^(AFHTTPRequestOperation *op,id responseObject){
        [loadmsg delayImagesRemove];
        NSDictionary *dic = (NSDictionary *)responseObject;
        NSLog(@"dic = %@", dic);
        
        flagPhone = [[dic objectForKey:@"flag"] integerValue];
        _message = [dic objectForKey:@"msg"];
        NSLog(@"flagPhone = %i", flagPhone);
        [self verifyPhoneNum];
        
    }failure:^(AFHTTPRequestOperation *op,NSError *error){
        [loadmsg delayImagesRemove];
        [PopMsg showMessage:@"网络异常，请重试" Lasttime:1.0f];
    }];
}


#pragma mark - 点击事件
//获取验证码
- (void)getCode:(UIButton *)btn
{
    if(_fieldPhone==nil || _fieldPhone.text.length==0){
        _tipLabel.text = @"※手机号码不能为空";
        _tipLabel.hidden = NO;
    }
    else if(_fieldPhone.text.length!=11){
        _tipLabel.text = @"※手机号码位数不对";
        _tipLabel.hidden = NO;
    }
    else {
        [self verifyCodeRequest];
    }
}

- (void)timer:(NSTimer*)timer
{
    _timeLabel.text = [NSString stringWithFormat:@"剩余时间%i秒",k-1];
    
    if (k==0) {
        _btnGetCode.enabled = YES;
        [_btnGetCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        _timeLabel.hidden = YES;
        [_timer invalidate];
        _timer = nil;
    }
    k--;
}

//下一步
- (void)btnNextClicked:(id)sender
{
    [self verifyPhoneRequest];
}

- (void)verifyPhoneNum
{
    //验证码错误，提示“验证码错误，请重新输入”
    if (flagPhone == -1) {
        [PopMsg showMessage:_message Lasttime:1.0f];
        _tipLabel.text = @"※验证码错误请重新输入";
        _tipLabel.hidden = NO;
    }
    //已注册已激活，提示"该号码已经被注册，请使用其他号码"
    else if (flagPhone == 2) {
        _tipLabel.hidden = YES;
        _btnGetCode.enabled = YES;
        [_btnGetCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        _timeLabel.hidden = YES;
        [_timer invalidate];
        _timer = nil;
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"该号码已经被激活，请使用其他号码" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
        [alert show];
    }
    //未注册，继续注册，进入第二步【身份验证】
    else if (flagPhone == 0) {
        _tipLabel.hidden = YES;
        _btnGetCode.enabled = YES;
        [_btnGetCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        _timeLabel.hidden = YES;
        [_timer invalidate];
        _timer = nil;
//        NSUserDefaults *defaults1 = [NSUserDefaults standardUserDefaults];
//        [defaults1 setObject:_fieldPhone.text forKey:@"phoneNo"];
//        
//        NSUserDefaults *defaults2 = [NSUserDefaults standardUserDefaults];
//        [defaults2 setObject:_fieldCode.text forKey:@"verifyCode"];
//
//        NameViewController *nameCtrl = [NameViewController new];
//        [self.navigationController pushViewController:nameCtrl animated:YES];
        [PopMsg showMessage:@"尚未注册，请联系客服" Lasttime:1.0f];
    }
    //已注册未激活，转至第四步【设置密码】
    else if (flagPhone == 1) {
        _tipLabel.hidden = YES;
        _btnGetCode.enabled = YES;
        [_btnGetCode setTitle:@"获取验证码" forState:UIControlStateNormal];
        _timeLabel.hidden = YES;
        [_timer invalidate];
        _timer = nil;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:_fieldPhone.text forKey:@"phoneNo"];
        
        SetPasswordViewController *setpwd = [SetPasswordViewController new];
        setpwd.flag = flagPhone;
        [self.navigationController pushViewController:setpwd animated:YES];
    }
}

//收起键盘
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    [_fieldPhone resignFirstResponder];
    [_fieldCode resignFirstResponder];
}

#pragma mark - UITextFieldDelegate

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if (textField == _fieldPhone) {
        if (textField.text.length >= 11)
        {
            if ([string isEqual:@""])
            {
                return YES;
            }
            return NO;
        }
    }
    return YES;
}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
    if (_fieldPhone.text.length == 11 && _fieldCode.text.length == result.length && result.length) {
        [self enableButton:_btnNext];
    }
    else {
        [self disableButton:_btnNext];
    }
}

#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
